<?php
namespace App\Modules\Admin\Services;

use App\Models\Admin\SysRole;
use App\Models\Admin\SysUser;
use Illuminate\Support\Str;

class RoleService extends AdminService
{
    protected $model = SysRole::class;

    public function getQueryBuilder(Array $data)
    {
        $this->queryBuilder = SysRole::query();
        if(isset($data['keywords']) && strlen($data['keywords']) > 0) {
            $this->queryBuilder->where('name', $data['keywords']);
        }

        if(isset($data['sort_by']) && isset($data['order']) && in_array(Str::lower($data['order']), ['asc', 'desc'])) {
            $this->queryBuilder->orderBy($data['sort_by'], $data['order']);
        } else {
            $this->queryBuilder->orderBy('id', 'desc');
        }
    }

    public function options()
    {
        return SysRole::select('id', 'name')->get();
    }

    public function getRoleMenuIds(Int $roleId)
    {
        $role = SysRole::find($roleId);

        return $role->permissions->pluck('id');
    }

    public function assignPermission(Int $roleId, Array $permissionIds)
    {
        $role = $this->model::find($roleId);

        return $role->permissions()->sync($permissionIds);
    }
}